package com.ezlcp.form.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.base.search.QueryFilter;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.DicValue;
import com.ezlcp.form.entity.Dictionary;
import com.ezlcp.form.service.DictionaryServiceImpl;
import com.ezlcp.form.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/form/dictionary")
@Tag(name = "数据字典")
public class DictionaryController extends BaseController<Dictionary> {
    @Autowired
    DictionaryServiceImpl dictionaryService;

    @Override
    public BaseService getBaseService() {
        return dictionaryService;
    }

    @Operation(summary = "查询字典主表")
    @PostMapping("/getDictionary")
    public JsonResult getDictionary(@Parameter(description = "字典关键字列表") @RequestParam("dicKeyList") String dicKeyList) {
        return JsonResult.getSuccessResult(dictionaryService.getByDicKey(dicKeyList), "common.selSuccess");
    }

    @Operation(summary = "获取数据字典记录以及其对应的下拉选项")
    @PostMapping("/get")
    @Override
    public JsonResult<Dictionary> get(@Parameter(description = "词典ID") @RequestParam("pkId") String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.handleSuccess");
        var data = dictionaryService.getById(pkId);
        result.setData(data);
        return result;
    }

    @Operation(summary = "检查字典Key是否重复")
    @PostMapping("checkKey")
    public JsonResult checkKey(@Parameter(description = "字典Key") @RequestParam("dicKey") String dicKey,
                               @Parameter(description = "字典Id") @RequestParam(value = "dicId", required = false) String dicId) {
        boolean repeat = dictionaryService.checkKeyRepeat(dicKey, dicId);
        if (repeat) {
            //关键字不能重复，请重新输入
            return JsonResult.Fail("dataDict.keyRepeat");
        }
        return JsonResult.Success("common.handleSuccess");
    }

    @Operation(summary = "保存字典记录，及下拉项子表记录")
    @PostMapping("/saveDict")
    public JsonResult saveDict(@RequestBody JSONObject data) {
        var master = data.getObject("master", Dictionary.class);
        var details = data.getJSONArray("details");
        if (master == null || details == null) {
            return JsonResult.Fail("common.paramError");
        }
        boolean repeat = dictionaryService.checkKeyRepeat(master.getDicKey(), master.getDicId());
        if (repeat) {
            //关键字不能重复，请重新输入
            return JsonResult.Fail("dataDict.keyRepeat");
        }
        String delIds = data.getString("deleteIds");
        String msg = dictionaryService.saveDictAndValues(master, details, delIds);
        if (StringUtils.isNotEmpty(msg)) {
            return JsonResult.Fail(msg);
        }
        logService.saveSystemLog(getComment(), "save", null, JSON.toJSONString(data));
        return JsonResult.Success("common.handleSuccess");
    }

    @Operation(summary = "根据主键ID删除记录", description = "删除一条记录")
    @PostMapping("del")
    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.Fail("common.paramError");
        }
        //TODO 判断是否被自定义表单引用
        dictionaryService.delDict(id);
        JsonResult result = JsonResult.Success("common.delSuccess");
        logService.saveSystemLog(getComment(), "delete", id, "");
        return result;
    }

    @Override
    public JsonResult save(Dictionary entity, BindingResult validResult) throws Exception {
        return JsonResult.Fail("common.apiClose");
    }

    @Override
    protected void handleFilter(QueryFilter filter) {
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            filter.addQueryParam("Q_dic.tenant_id_S_EQ", tenantId);
        }
    }

    @Override
    public String getComment() {
        return "数据字典";
    }
}